import {useStore} from "@/stores";
import { handleMenus,} from "@/utils/SystemUtil";
import {loadAuthUserAsset, userToken} from "@/apis";
import MainLayout from "@/views/layouts/MainLeftTabout.vue";
import {lookupPlatform} from "@/apis/sop";

const loadUserAssets = async () => {
    const retMenus: any = [];
    const store = useStore();
    const assets = await loadAuthUserAsset();

    if (assets.data) {
        handleMenus(retMenus, assets.data.menus);
        store.updateUserAssets(assets.data);
        store.buildRouteMenus(MainLayout, retMenus, '/dashboard');
    }
}

// 登录成功
export async function handleLoginSuccess(){
    await loadPlatform();
    await loadUserAssets();
}

export async function loadPlatform() {
    const store = useStore();

    const result: any = await lookupPlatform({
        platformId: import.meta.env.VITE_APP_PLATFORM
    });
    if (result && result.data) {
        store.setCurrentPlatform(result.data);
    }
}

export async function executeLoginByCode(code: string, home: string) {
    if (code) {
        const result = await userToken(code);
        if (result && result.code === 0) {
            const store = useStore();
            // 保存登录返回的用户信息
            store.setUserData(result.data);
            await handleLoginSuccess(home);
            return true;
        }
    }
    return false;
}
